<template>
  <div class="container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>试题录入</span>
      </div>
      <div class="warp">
        <el-form ref="form" :rules="rules" :model="form" label-width="100px">
          <el-form-item label="学科:" prop="subjectID">
            <el-select v-model="form.subjectID" placeholder="请选择" class="inpw">
              <el-option
                :label="val.subjectName"
                :value="val.id"
                v-for="val in sublist"
                :key="val.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="目录:" prop="catalogID">
            <el-select v-model="form.catalogID" placeholder="请选择" class="inpw">
              <el-option
                :label="val.directoryName"
                :value="val.id"
                v-for="val in dirlist"
                :key="val.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="企业:" prop="enterpriseID">
            <el-select v-model="form.enterpriseID" placeholder="请选择" class="inpw">
              <el-option
                :label="val.company"
                :value="val.id"
                v-for="val in comlist"
                :key="val.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="城市:" prop="province">
            <el-select v-model="form.province" placeholder="请选择" class="inpww" @change="getcitys">
              <el-option
                :label="val"
                v-for="(val,index) in provinceslist"
                :key="index"
                :value="val"
              ></el-option>
            </el-select>
            <el-select v-model="form.city" placeholder="请选择" class="inpww">
              <el-option :label="val" :value="val" v-for="(val,index) in cityslist" :key="index"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="方向:" prop="direction">
            <el-select v-model="form.direction" placeholder="请选择" class="inpw">
              <el-option
                :label="val"
                :value="val"
                v-for="(val,index) in directionlist"
                :key="index"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="题型:" prop="questionType" >
            <el-radio-group v-model="form.questionType" @change="questchange">
              <el-radio
                :label="val.value"
                v-for="(val,index) in questionType"
                :key="index"
              >{{val.label}}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="难度:">
            <el-radio-group v-model="form.difficulty">
              <el-radio :label="val.value" v-for="(val,index) in difficulty" :key="index">{{val.label}}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="题干:" prop="question">
            <!-- 富文本 -->
            <quillEditor
              v-model="form.question"
              :options="editorOption"
              style="height:100px; margin-bottom:100px;"
            ></quillEditor>
          </el-form-item>
          <el-form-item label="选项:"  v-if="isshow">
            <!-- options -->
            <!-- 单项选择区 -->
            <el-radio-group v-model="checkedName" v-if="form.questionType==='1'">
              <el-row class="xuanxiang" v-for="(val,index) in form.options" :key="index">
                <el-col :span="24">
                  <el-radio :label="val.code" @change="radioChange(index)">
                    {{val.code }}:
                    <el-input placeholder="请输入" v-model="val.title"></el-input>
                  </el-radio>
                  <UploadImg v-model="val.img"></UploadImg>
                </el-col>
              </el-row>
              <el-button type="danger" :disabled="form.questionType==='1'">点击添加选项</el-button>
            </el-radio-group>

            <!-- 多项选择区 -->
             <el-checkbox-group v-model="checkedCities" v-if="form.questionType==='2'">
              <el-row class="xuanxiang"  v-for="(val,index) in form.options" :key="index">
                <el-col :span="24">
                  <el-checkbox :label="val.code" name="type" @change="checkBoxChange(val)">
                  {{val.code}}  <el-input placeholder="请输入" v-model="val.title"></el-input>
                  </el-checkbox>
                  <UploadImg v-model="val.img"></UploadImg>
                </el-col>
              </el-row>
            <el-button type="danger" @click="addoptions">点击新增选项</el-button>
            </el-checkbox-group>
          </el-form-item>

          <el-form-item label="解析视频:">
            <el-input class="inpw" v-model="form.videoURL"></el-input>
          </el-form-item>
          <el-form-item label="答案解析:" prop="answer">
            <!-- 富文本 -->
            <quillEditor
              v-model="form.answer"
              :options="editorOption"
              style="height:100px; margin-bottom: 100px;"
            ></quillEditor>
          </el-form-item>
          <el-form-item label="题目备注:" prop="remarks">
            <el-input
              type="textarea"
              :rows="2"
              placeholder="请输入内容"
              v-model="form.remarks"
              class="inpw"
            ></el-input>
          </el-form-item>
          <el-form-item label="试题标签:" prop="tags">
            <el-select
              class="inpw"
              v-model="form.tags"
              placeholder="请选择文章标签"
            >
            <!--   multiple
              filterable
              allow-create
              default-first-option -->
              <el-option
                v-for="item in tags"
                :key="item.id"
                :label="item.tagName"
                :value="item.tagName"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmit">{{$route.query.id ?'立即修改':'立即创建'}}</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script>
// 引入上传图片组件
import UploadImg from '@/components/UploadImg/index'
// 导入样式
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
// , ,  按需导出需要的文件
import { difficulty, direction, questionType } from '@/api/hmmm/constants'
// 获取城市
import { provinces, citys } from '@/api/hmmm/citys.js'
// 引入富文本组件
import { quillEditor } from 'vue-quill-editor'
// 引入学科列表API
import { list as sublist } from '@/api/hmmm/subjects'
// 引入目录列表API
import { list as dirlist } from '@/api/hmmm/directorys'
// 引入企业列表API
import { list as comlist } from '@/api/hmmm/companys'
// 获取标签列表API
import { list as tagslist } from '@/api/hmmm/tags'
// 引入题库API
import { update, add, detail } from '@/api/hmmm/questions'
export default {
  components: {
    quillEditor,
    UploadImg
  },
  created () {
    // 获取市方法
    this.getprovinces()
    // 获取区方法
    this.getcitys()
    // 获取学科列表方法
    this.getlist()
    // 获取目录列表方法
    this.getdirlist()
    // 获取企业列表的方法
    this.getcomlist()
    // 获取标签列表方法
    this.gettagslist()
    // 放置一个方法判断是否是从别的页面跳转过来的
    this.pageid()
  },
  data () {
    return {
      isshow: true, // 控制选项的显示和隐藏
      checkedCities: [], // 多选结果
      checkedName: '', // 单选结果
      questionType, // 题型
      difficulty, // 难度
      directionlist: direction, // 接收方向
      provinceslist: [], // 接收市
      cityslist: [], // 接收区
      sublist: [], // 接收学科列表
      dirlist: [], // 接收目录列表
      comlist: [], // 接收企业列表
      tags: [], // 接收标签列表
      form: {
        subjectID: '', // 学科
        catalogID: '', // 目录
        enterpriseID: '', // 企业
        province: '', // 城市
        difficulty: '1', // 难度
        questionType: '1', // 题型
        city: '', // 地区
        remarks: '', // 题目备注
        direction: '', // 方向
        question: '', // 题干
        options: [
          {
            code: 'A',
            title: '',
            img: '',
            isRight: false
          },
          {
            code: 'B',
            title: '',
            img: '',
            isRight: false
          },
          {
            code: 'C',
            title: '',
            img: '',
            isRight: false
          },
          {
            code: 'D',
            title: '',
            img: '',
            isRight: false
          }
        ], // 选项
        videoURL: '', // 解析视频
        answer: '', // 答案解析
        tags: ''// 试题标签
      },
      rules: {
        subjectID: [{ required: true, message: '请输入', trigger: 'blur' }],
        catalogID: [{ required: true, message: '请输入', trigger: 'blur' }],
        enterpriseID: [{ required: true, message: '请输入', trigger: 'blur' }],
        province: [{ required: true, message: '请输入', trigger: 'blur' }],
        city: [{ required: true, message: '请输入', trigger: 'blur' }],
        direction: [{ required: true, message: '请输入', trigger: 'blur' }],
        question: [{ required: true, message: '请输入', trigger: 'blur' }],
        answer: [{ required: true, message: '请输入', trigger: 'blur' }],
        remarks: [{ required: true, message: '请输入', trigger: 'blur' }],
        tags: [{ required: true, message: '请输入', trigger: 'blur' }]
      },
      editorOption: {
        placeholder: '',
        // 富文本配置项
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'], // 加粗，斜体，下划线，删除线
            ['blockquote', 'code-block'], // 引用，代码块
            [{ header: 1 }, { header: 2 }], // 几级标题
            [{ list: 'ordered' }, { list: 'bullet' }], // 有序列表，无序列表
            [{ indent: '-1' }, { indent: '+1' }], // 缩进
            ['image']
          ]
        }
      }
    }
  },
  methods: {
    // 获取标签列表
    async gettagslist () {
      const res = await tagslist()
      console.log('获取的标签列表是', res)
      this.tags = res.data.items
    },
    // 获取企业列表
    async getcomlist () {
      const res = await comlist()
      console.log('获取的企业列表是', res)
      this.comlist = res.data.items
    },
    // 获取目录列表
    async getdirlist () {
      const res = await dirlist()
      console.log('获取的目录列表是', res)
      this.dirlist = res.data.items
    },
    // 获取学科列表
    async getlist () {
      const res = await sublist()
      console.log('获取的学科列表是', res)
      this.sublist = res.data.items
    },
    // 获取市
    getprovinces () {
      this.provinceslist = provinces()
    },
    // 获取区
    async getcitys () {
      const e = await this.form.province
      console.log('当前点击的城市是', e)
      this.cityslist = await citys(e)
      this.form.city = this.cityslist[0]
    },
    // 监听复选框
    checkBoxChange (val) {
      if (this.checkedCities.length > 0) {
        this.checkedCities.forEach(e => {
          if (e === val.code) {
            val.isRight = true
          } else {
            val.isRight = false
          }
        })
      }
      console.log(this.checkedCities)
    },
    // 监听单选框
    radioChange (index) {
      this.form.options.forEach(e => {
        // 如果当前遍历对象等于数组对象 当前是被选择 设为true
        if (e === this.form.options[index]) {
          e.isRight = true
        } else {
          e.isRight = false
        }
      })
      console.log(this.form.options)
    },
    // 新增选项按钮
    addoptions () {
      const obj = {}
      // 将数字转换成字母 获取数组最后一个字母的下一个字母
      obj.code = String.fromCharCode(64 + parseInt(this.form.options.length + 1))
      // obj.id = String(this.form.options.length + 1)
      obj.title = ''
      obj.img = ''
      obj.isRight = false
      this.form.options.push(obj)
      console.log(this.form.options)
    },
    // 监听题型的变化
    questchange () {
      // 当题型为三的时候就让选项部分隐藏掉   如果不是题型三就显示
      this.form.questionType === '3' ? this.isshow = false : this.isshow = true
      // 把选择的单选框的值设置null 初始化
      this.form.options.forEach(e => {
        e.isRight = false
        e.title = ''
      })
      if (this.form.questionType === '1') {
        this.form.options.splice(4)
      }
      // 取消单选框选中状态
      this.checkedName = ''
      // 清空已选多选框
      this.checkedCities = []
    },
    // 基础题库添加
    async jcadd () {
      console.log(this.form)
      // 调用添加接口
      const res = await add(this.form)
      console.log(res)
      // 添加成功提示
      this.$message({
        message: '添加成功',
        type: 'success'
      })
      // 置空表单
      this.form = {
        subjectID: '', // 学科
        catalogID: '', // 目录
        enterpriseID: '', // 企业
        province: '', // 城市
        difficulty: '1', // 难度
        questionType: '1', // 题型
        city: '', // 地区
        remarks: '', // 题目备注
        direction: '', // 方向
        question: '', // 题干
        videoURL: '', // 解析视频
        answer: '', // 答案解析
        tags: '', //
        options: [
          {
            code: 'A',
            title: '',
            img: '',
            isRight: false
          },
          {
            code: 'B',
            title: '',
            img: '',
            isRight: false
          },
          {
            code: 'C',
            title: '',
            img: '',
            isRight: false
          },
          {
            code: 'D',
            title: '',
            img: '',
            isRight: false
          }
        ] // 选项
      }
      // 取消单选框选中状态
      this.checkedName = ''
      // 清空已选多选框
      this.checkedCities = []
    },
    // 获取当前题目详情
    async pageid () {
      // 声明一个变量来接收id
      const id = this.$route.query.id
      console.log('跳转过来的id是', id)
      const params = {
        id: id
      }
      if (id) {
        // 当页面有ID的时候
        try {
          // 调用接口获取当前页面详情
          const res = await detail(params)
          console.log('当前页面的详情是', res)
          this.form = res.data
          // 判断当前是否为单选框
          if (res.data.questionType === '1') {
            console.log('单选框·····')
            // 过滤出当前详情中被选中的内一项
            const newObj = res.data.options.filter(e => e.isRight)
            this.checkedName = newObj[0].code
          }
          // 如果 题型为复杂给多选框赋值 questionType === 2
          if (res.data.questionType === '2') {
            console.log('fu选框·····')
            // 过滤出 选中的复选框
            this.checkedCities = res.data.options.filter(e => e.isRight === 1).map(item => item.code)
            console.log(this.checkedCities)
          }
        } catch (error) {
          console.log(error)
        }
      }
    },
    // 修改题目方法
    async jcupdate () {
      // 调用修改接口
      const res = await update(this.form)
      console.log(res)
      // 修改成功提示
      this.$message({
        message: '修改成功',
        type: 'success'
      })
      // 返回上一层
      this.$router.go(-1)
    },
    // 提交表单
    onSubmit () {
      this.$refs.form.validate(async valid => {
        if (valid) {
          // if (this.$route.query.id) {
          //   // 有ID就调用修改接口
          //   await this.jcupdate()
          // } else {
          //   // 没ID就添加接口
          //   await this.jcadd()
          // }
          this.$route.query.id ? await this.jcupdate() : await this.jcadd()
        } else {
          this.$message({
            message: '请填写必填项',
            type: 'error'
          })
        }
      })
    }
  }
}
</script>

<style scoped lang='scss'>
.container {
  margin: 30px;
}
.inpw {
  width: 400px;
}
.inpww {
  width: 200px;
}
</style>
<style lang='scss'>
.xuanxiang {
  margin: 40px 0;
  position: relative;

}
</style>
